/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

// 多选开关
var DataTableMuli = false;

window.current_flow_id = false;

window.current_groupid = false;
// 选中tr
var dataTableSelectedTr = false;

var row = false;

window.identify = false;

window.submit_identify = false;//提交种类

window.data_add = false;

var flowSm = false;

// datatable 配置项
var DataTableConfig = {
    "bPaginate": false,
    "bLengthChange": false,
    "iDisplayLength": 6000,
    "bFilter": true,
    "bInfo": false,
    "bAutoWidth": false,
    "order": [[0, 'desc'], [1, 'desc']],
    "fnInitComplete": function() {
        loadTop($('#_topLeftPlace').html());
        dataTableLis();
    }
};

$(function() {

    // parent.clearSelectedTr();
    if ($('#nofilter').length > 0) {
        DataTableConfig.bFilter = false;
    }
    $('.dTable').dataTable(DataTableConfig);
    $('.dataTables_filter').addClass('clearfix');
    $('.search-w-box input').attr('placeholder', '输入搜索内容');

    //id=modify的标签调用fancybox
    $('#modify').click(function() {
        $('#modify').fancybox({
            'openEffect': 'fade',
            'closeEffect': 'elastic',
            'openSpeed': 'fast',
            'closeSpeed': 'fast',
            'overlayColor': 'blue',
            'scrolling': 'no',
            afterShow: function() {
                var data = getSelectedTr();
                $('#operator_id').val(data[1]);
                $('#operator_name').val(data[2]);
                // 不显示密码
                // $('#operator_password').val(data[2]);
                //修改时显示选中下拉框的文本
                var options = $('#operator_type_id').find('option');
                options.each(function(index, node) {
                    var re1 = new RegExp($(node).text());
                    if (data[3].match(re1)) {
                        $(node).attr('selected', 'selected');
                    }
                });
                var department_options = $('#department_select').find('option');
                department_options.each(function(index, node) {
                    var re1 = new RegExp($(node).text());
                    if (data[3].match(re1)) {
                        $(node).attr('selected', 'selected');
                    }
                });
                show_all();
            }
        });
    });


    /**
     * 车间修改
     */
    $('#department_modify').click(function() {
        $('#department_modify').fancybox({
            'openEffect': 'fade',
            'closeEffect': 'elastic',
            'openSpeed': 'fast',
            'closeSpeed': 'fast',
            'overlayColor': 'blue',
            'scrolling': 'no',
            afterShow: function() {
                var data = getSelectedTr();
                $('#department_name').val(data[1]);
                $('#sort').val(data[2]);
            }
        });


    });

    //id=add的标签调用fancybox
    $('#add').click(function() {
        $('#add').fancybox({
            'openEffect': 'fade',
            'closeEffect': 'elastic',
            'openSpeed': 'fast',
            'closeSpeed': 'fast',
            'overlayColor': 'blue',
            'scrolling': 'no',
            'afterShow': function() {
            }
        });
    });

    //流程设置添加车间按钮调用fancybox
    $('#flow_department_add').click(function() {
        $('#flow_department_add').fancybox({
            'openEffect': 'fade',
            'closeEffect': 'elastic',
            'openSpeed': 'fast',
            'closeSpeed': 'fast',
            'overlayColor': 'blue',
            'scrolling': 'no',
            'afterShow': function() {
                var data = getSelectedTr();
                var options = $('#flow_department_select').find('option');
                options.each(function(index, node) {
                    if ($(node).text() === data[0]) {
                        $(node).attr('selected', 'selected');
                    }
                });

            }
        });
    });

    /**
     * 购买原料，id=buy的标签调用fancybox
     */
    $('#buy').click(function() {
        $('#buy').fancybox({
            'openEffect': 'fade',
            'closeEffect': 'elastic',
            'openSpeed': 'fast',
            'closeSpeed': 'fast',
            'overlayColor': 'blue',
            'scrolling': 'no',
            'afterShow': function() {
                var data = getSelectedTr();
                var options = $('#material_name_select').find('option');
                options.each(function(index, node) {
                    if ($(node).text() === data[0]) {
                        $(node).attr('selected', 'selected');
                    }
                });

                var type = $('#type_select').find('option');
                type.each(function(index, node) {
                    if ($(node).text() === data[1]) {
                        $(node).attr('selected', 'selected');
                    }
                });

                var measurement = $('#measurement_select').find('option');
                measurement.each(function(index, node) {
                    if ($(node).text() === data[2]) {
                        $(node).attr('selected', 'selected');
                    }
                });
            }
        });
    });

    //id=check_detail查看详情调用fancybox
    $('#check_detail').click(function() {
        $('#check_detail').fancybox({
            'openEffect': 'fade',
            'closeEffect': 'elastic',
            'openSpeed': 'fast',
            'closeSpeed': 'fast',
            'overlayColor': 'blue',
            'scrolling': 'no',
            'afterShow': function() {

            }
        });
    });


    //id=ha的标签调用fancybox
    $('#ha').click(function() {
        $('#ha').fancybox({
            'openEffect': 'fade',
            'closeEffect': 'elastic',
            'openSpeed': 'fast',
            'closeSpeed': 'fast',
            'overlayColor': 'blue',
            'scrolling': 'no',
            'afterShow': function() {
            }
        });
    });

    //车间流程设置页面产品修改，id=product_modify的标签调用fancybox
    $('#product_modify').click(function() {
        $('#product_modify').fancybox({
            'openEffect': 'fade',
            'closeEffect': 'elastic',
            'openSpeed': 'fast',
            'closeSpeed': 'fast',
            'overlayColor': 'blue',
            'scrolling': 'no',
            'afterShow': function() {
                var data = getSelectedTr();
                $('#flow_name').val(data[0].text);
            }
        });
    });

    $('#modify_group').click(function() {
        $('#modify_group').fancybox({
            'openEffect': 'fade',
            'closeEffect': 'elastic',
            'openSpeed': 'fast',
            'closeSpeed': 'fast',
            'overlayColor': 'blue',
            'scrolling': 'no',
            'afterShow': function() {
                var data = getSelectedTr();
                $('#modify_input').val();
            }
        });
    });

    /**
     * 选择产品
     */
    $('#addorder-selectProduct').fancybox({
        'openEffect': 'fade',
        'openSpeed': 'fast',
        'closeSpeed': 'fast',
        'overlayColor': 'blue',
        'scrolling': 'no',
        'afterShow': function() {
            $('#pdwrap').height($('.fancybox-inner').eq(0).height());
            $('#pdwrap2').height($('.fancybox-inner').eq(0).height() - 45);
            // datatable
            DataTableConfig.bFilter = false;
            DataTableMuli = true;
            $('#productList').dataTable(DataTableConfig);
            $('#productlist-addbtn').click(function() {
                // 多选结束
                var datas = getMuliSelectedTrs();
                var html = '';
                for (var i in datas) {
                    if (datas[i][0]) {
                        html += '<tr style="border-left:1px solid #dedede" class="plS" data-id="' + datas[i][0].id + '">';
                        html += '<td data-id="' + datas[i][0].id + '">' + datas[i][2] + '(' + datas[i][3] + ')</td>';
                        html += '<td><input class="inputSmall cou" value="1" /></td>';
                        html += '<td><input class="inputSmall tot" style="width:50px" /></td>';
                        html += '<td><input class="inputSmall sum" style="width:50px" /></td>';
                        html += '<td><input class="inputSmall tot1" style="width:50px" /></td>';
                        html += '<td><input class="inputSmall sum1" style="width:50px" /></td>';
                        html += '<td><a class="delete button" href="javascript:;" >删除</a></td>';
                        html += '</tr>';
                    }
                }
                window.cusorderSum = 0;
                $('#productListSelected tbody').append(html).show();
                $('#productListWrap').show();
                $(":text").focus(function() {
                    $(this).select();
                });
                $.fancybox.close();
                resize();
                calculate();
                delete_tr();
            });

            // 不显示已选择的行
            $('.plS').each(function(i, node) {
                $('#pl-' + $(node).attr('data-id')).remove();
            });
        }
    });

    /**
     * 选择原料
     */
    $('#addorder-selectMaterial').fancybox({
        'openEffect': 'fade',
        'closeEffect': 'elastic',
        'openSpeed': 'fast',
        'closeSpeed': 'fast',
        'overlayColor': 'blue',
        'scrolling': 'no',
        'afterShow': function() {
            // datatable
            DataTableConfig.bFilter = false;
            DataTableMuli = true;
            $('#productList').dataTable(DataTableConfig);
            $('#productlist-addbtn').click(function() {
                // 多选结束
                var datas = getMuliSelectedTrs();
                var html = '';
                for (var i in datas) {
                    html += '<tr style="border-left:1px solid #dedede" class="plS" data-id="' + datas[i][2] + '">';
                    html += '<td>' + datas[i][1] + '</td>';
                    html += '<td data-id="' + datas[i][2] + '">' + datas[i][3] + '</td>';
                    html += '<td>' + datas[i][4] + '</td>';
                    html += '<td><input class="inputSmall cou" value="1" /></td>';
                    html += '<td><input class="inputSmall tot" style="width:50px" /></td>';
                    html += '<td><input class="inputSmall sum" style="width:50px" /></td>';
                    html += '<td><a class="delete button" href="javascript:;" >删除</a></td>';
                    html += '</tr>';
                }
                window.cusorderSum = 0;
                $('#productListSelected tbody').append(html).show();
                $('#productListWrap').show();
                $.fancybox.close();
                resize();
                calculate();
                delete_tr();
            });

            // 不显示已选择的行
            $('.plS').each(function(i, node) {
                $('#pl-' + $(node).attr('data-id')).remove();
            });
        }
    });

    fnFancyBox('#materialSpeard-btn', function() {
        // datatable
        DataTableConfig.bFilter = false;
        DataTableMuli = true;
        $('#productList').dataTable(DataTableConfig);
        $('#productlist-addbtn').click(function() {
            // 多选结束
            var datas = getMuliSelectedTrs();
            var html = '';
            for (var i in datas) {
                html += '<tr style="border-left:1px solid #dedede" class="plS" data-id="' + datas[i][2] + '">';
                html += '<td>' + datas[i][1] + '</td>';
                html += '<td data-id="' + datas[i][2] + '">' + datas[i][3] + '</td>';
                html += '<td>' + datas[i][4] + '</td>';
                html += '<td><input class="inputSmall cou" value="1" type="number" /></td>';
                html += '<td><a class="delete button del show" href="javascript:;" >删</a></td>';
                html += '</tr>';
            }
            window.cusorderSum = 0;
            $('#productListSelected tbody').append(html).show();
            $('#productListWrap').show();
            $.fancybox.close();
            resize();
            calculate();
            delete_tr();
        });

        // 不显示已选择的行
        $('.plS').each(function(i, node) {
            $('#pl-' + $(node).attr('data-id')).remove();
        });
    });

    /**
     * 生产订单选择原料
     */
    $('#material_order_select').fancybox({
        'openEffect': 'fade',
        'closeEffect': 'elastic',
        'openSpeed': 'fast',
        'closeSpeed': 'fast',
        'overlayColor': 'blue',
        'scrolling': 'no',
        'afterShow': function() {
            // datatable
            DataTableConfig.bFilter = false;
            DataTableMuli = true;
            $('#productList').dataTable(DataTableConfig);
            $('#productlist-addbtn').click(function() {
                // 多选结束
                var datas = getMuliSelectedTrs();
                var html = '';
                for (var i in datas) {
                    html += '<tr style="border-left:1px solid #dedede" class="plS" data-id="' + datas[i][2] + '">';
                    html += '<td>' + datas[i][1] + '</td>';
                    html += '<td data-id="' + datas[i][2] + '">' + datas[i][3] + '</td>';
                    html += '<td>' + datas[i][4] + '</td>';
                    html += '<td><input class="inputSmall cou" value="1" /></td>';
                    html += '<td><a class="delete button" href="javascript:;" >删除</a></td>';
                    html += '</tr>';
                }
                window.cusorderSum = 0;
                $('#productListSelected tbody').append(html).show();
                $('#productListWrap').show();
                $.fancybox.close();
                resize();
                delete_tr();
            });

            // 不显示已选择的行
            $('.plS').each(function(i, node) {
                $('#pl-' + $(node).attr('data-id')).remove();
            });
        }
    });

    var bottom = $('.iframe_body').find('#bottom')
    if (bottom.length === 0) {
        $('.iframe_body').css("margin-bottom", "0")
    }

    //添加客户分组
    fnFancyBox('#group_add', function() {
        $('#group_save').click(function() {
            var gdata = {};
            gdata.statement = 'add';
            gdata.name = $('#add_input').val();
            customerGroupSave(gdata);
        });
    });

    //修改客户分组
    fnFancyBox('#edit_group', function() {
        var data = getSelectedTr();
        $('#modify_input').val($.trim(data[0].text));
        $('#group_save').click(function() {
            var data = getSelectedTr();
            var gdata = {};
            gdata.id = data[0].id;
            gdata.statement = 'update';
            gdata.name = $('#modify_input').val();
            customerGroupSave(gdata);
        });
    });

    // 添加原料
    fnFancyBox('#materalInfoAdd', function() {
        $('#materialInfob1').click(function() {
            var mdata = {};
            mdata.statement = 'add';
            mdata.code = $('#material_code').val();
            mdata.name = $('#material_name').val();
            mdata.type = $('#material_type').val();
            mdata.number = $('#material_count').val();
            mdata.remark = $('#remark').val();
            materialInfoSave(false, mdata);
        });
    });

    // 编辑原料
    fnFancyBox('#materalInfoEdit', function() {
        var data = getSelectedTr();
        $('#material_code').val(data[0]);
        $('#material_name').val(data[1].text);
        $('#material_type').val(data[2]);
        $('#remark').val(data[3]);
        $('#material_count').val(data[4]);
        $('#materialInfob1').click(function() {
            var mdata = {};
            var data = getSelectedTr();
            mdata.id = data[1].id;
            mdata.statement = 'update';
            mdata.code = $('#material_code').val();
            mdata.name = $('#material_name').val();
            mdata.type = $('#material_type').val();
            mdata.number = $('#material_count').val();
            mdata.remark = $('#remark').val();
            materialInfoSave(data[1].id, mdata);
        });
    });

    // 添加产品信息
    fnFancyBox('#productInfoAdd', function() {
        $('#productInfob1').click(function() {
            var mdata = {};
            mdata.statement = 'add';
            mdata.product_code = $('#product_code').val();
            mdata.model = $('#product_name').val();
            mdata.gongyi = $('#product_type').val();
            mdata.number = $('#product_count').val();
            mdata.material = '';
            productInfoSave(false, mdata);
        });
    });

    // 编辑产品信息
    fnFancyBox('#productInfoEdit', function() {
        var data = getSelectedTr();
        $('#product_code').val(data[1]);
        $('#product_name').val(data[2]);
        $('#product_type').val(data[3]);
        $('#product_count').val(data[4]);
        $('#productInfob1').click(function() {
            var mdata = {};
            var data = getSelectedTr();
            mdata.id = data[0];
            mdata.statement = 'update';
            mdata.model = $('#product_name').val();
            mdata.gongyi = $('#product_type').val();
            mdata.number = $('#product_count').val();
            mdata.material = '';
            mdata.product_code = $('#product_code').val();
            productInfoSave(mdata.id, mdata);
        });
    });

    $('.buttonX').fancybox({
        'openEffect': 'fade',
        'closeEffect': 'elastic',
        'openSpeed': 'fast',
        'closeSpeed': 'fast',
        'width': '300px'
    });

    fnFancyBox('#producefin', function() {
        $('#fin-text').html('订单编号：' + $('#pdcode').val());
        $('#fin-text2').html('预计产量：' + $('#pdnumber').val());
    });

    fnFancyBox('#add_customer', function() {
        $('#cus_name').focus();
    });

    fnFancyBox('#edit_customer', function() {
        $('#cus_name').focus();

        var pdata = getSelectedTr();
        $('#cus_name').val(pdata[1]);
        $('#cus_phone').val(pdata[2]);
        $('#cus_qq').val(pdata[3]);
        $('#cus_email').val(pdata[4]);
        $('#cus_address').val(pdata[5]);

        // current_groupid
        $('#group_select1').find('option').each(function(i, node) {
            if (parseInt($(node).val()) === current_groupid) {
                $(node).attr('selected', 'selected');
            }
        });
    });

    //判断客户订单状态
    if ($('#state').text() == '已发货') {
        $('#wait_for_produce').hide();
        $('#wait_for_send').hide();
        $('#already_send').hide();
    } else if ($('#state').text() == '已完成') {
        $('#wait_for_produce').hide();
        $('#wait_for_send').hide();
        $('#already_send').hide();
        $('#finish_order').hide();
    }
    if ($('#material_state').text() == '已采购') {
        $('#wait_for_produce').hide();
        $('#wait_for_send').hide();
        $('.finish_order').hide();
    }
});//loading函数结尾

/**
 * 客户编辑
 * @returns {undefined}
 */
function customerSave() {
    if ($('#cusMod').val() === 'add') {
        // 添加
        var data = {
            gid: $('#group_select1').val(),
            name: $('#cus_name').val(),
            tel: $('#cus_phone').val(),
            qq: $('#cus_qq').val(),
            e_mail: $('#cus_email').val(),
            address: $('#cus_address').val(),
            statement: 'add'
        };
        $.post('/pages/handler/customer.php', data, function(r) {
            if (parseInt(r) === 1) {
                parent.Alert('添加成功');
                loadCusDataByGroupId(current_groupid);
            } else {
                parent.Alert('添加失败');
            }
            $.fancybox.close();
        });
    } else {
        // 修改
        var id_data = getSelectedTr();
        var data = {
            gid: $('#group_select1').val(),
            id: id_data[0],
            name: $('#cus_name').val(),
            tel: $('#cus_phone').val(),
            qq: $('#cus_qq').val(),
            e_mail: $('#cus_email').val(),
            address: $('#cus_address').val(),
            statement: 'update'
        }
        $.post('/pages/handler/customer.php', data, function(r) {
            if (parseInt(r) === 1) {
                parent.Alert('修改成功');
                loadCusDataByGroupId(current_groupid);
                $('#group').hide();
            } else {
                parent.Alert('修改失败');
            }
            $.fancybox.close();
        });
    }
}

/**
 * 保存操作员
 * @returns {undefined}
 */
function operatorSave() {
    if (parseInt($('#operator_type_id option:selected').val()) === 4) {
        var pdata = getSelectedTr();
        var id = pdata[1];
        var name = $('#operator_name').val();
        var pass = $('#operator_password').val();
        var user_type_id = $('#operator_type_id').val();
        var department_id = $('#department_select option:selected').val();
        var data = {
            statement: 'update',
            id: id,
            name: name,
            password: pass,
            user_type_id: user_type_id,
            department_id: department_id
        };
        $.post('/pages/handler/operator_management.php', data, function(r) {
            if (parseInt(r) === 1) {
                parent.Alert('修改成功！');
                window.location.reload();
            } else {
                parent.Alert('修改失败！');
            }
        });
    } else {
        var pdata = getSelectedTr();
        var id = pdata[1];
        var name = $('#operator_name').val();
        var pass = $('#operator_password').val();
        var user_type_id = $('#operator_type_id').val();
        var department_id = '';
        var data = {
            statement: 'update',
            id: id,
            name: name,
            password: pass,
            user_type_id: user_type_id,
            department_id: department_id
        };
        $.post('/pages/handler/operator_management.php', data, function(r) {
            if (parseInt(r) === 1) {
                parent.Alert('修改成功！');
                window.location.reload();
            } else {
                parent.Alert('修改失败！');
            }
        });
    }
}

/**
 * datatable事件监听
 * @returns {undefined}
 */
function dataTableLis(tableId, sel) {
    tableId = tableId || '.dTable';
    // 是否可以选中 默认true
    sel = sel || true;
    $(tableId + ' tbody tr').unbind('click').click(function() {
        if (sel) {
            if (!DataTableMuli) {
                // 单选
                $(tableId + ' tbody tr.click').removeClass('click');
                $(this).addClass('click');
                dataTableSelectedTr = $(this);
            } else {
                // 多选
                var cb = $(this).find('input:checkbox')[0];
                if ($(this).hasClass('click')) {
                    if (cb) {
                        cb.checked = false;
                    }
                    $(this).toggleClass('click');
                } else {
                    $(this).addClass('click');
                    if (cb) {
                        cb.checked = true;
                    }
                }
            }
        }
        $('.button.del,.button.edit').css('display', 'inline-block');
    }).mouseover(function() {
        $(this).addClass('hover');
    }).mouseout(function() {
        $(this).removeClass('hover');
    });
}

/**
 * 添加操作员
 */
function operatorAdd() {
    if ($('#operator_type_id option:selected').val() == 4) {
        var name = $('#operator_name').val();
        var pass = $('#operator_password').val();
        var user_type_id = $('#operator_type_id').val();
        var department_id = $('#department_select option:selected').val();
        $.post('/pages/handler/operator_management.php', {
            statement: 'add',
            name: name,
            password: pass,
            user_type_id: user_type_id,
            department_id: department_id
        }, function(r) {
            if (r == 1) {
                parent.Alert('添加成功！');
                window.location.reload();
            } else {
                parent.Alert('添加失败，用户名已存在！');
            }
        });
    } else {
        var name = $('#operator_name').val();
        var pass = $('#operator_password').val();
        var user_type_id = $('#operator_type_id').val();
        var department_id = '';
        $.post('/pages/handler/operator_management.php', {
            statement: 'add',
            name: name,
            password: pass,
            user_type_id: user_type_id,
            department_id: department_id
        }, function(r) {
            if (r == 1) {
                parent.Alert('添加成功！');
                window.location.reload();
            } else {
                parent.Alert('添加失败，用户名已存在！');
            }
        });
    }
}

/**
 * 删除操作员
 * @returns {undefined}
 */
function operatorDelete(node) {
    var data = getSelectedTr();
    if (data !== false) {
        if (confirm('你确认要删除吗')) {
            $.post('/pages/handler/operator_management.php', {
                statement: 'delete',
                id: data[1]
            }, function(r) {
                if (r == 1) {
                    parent.Alert('删除成功！');
                    fnDeleteSelectedTR();
                } else {
                    parent.Alert('删除失败！');
                }
            });
        }
    }
}

/**
 * 添加生产订单
 * @returns {undefined}
 */
function add_product_orders() {
    var materials = [];
    $('#productListSelected tbody tr').each(function(i, node) {
        var tds = $('td', node);
        materials.push({
            material_id: tds.eq(1).attr('data-id'),
            number: tds.find('.inputSmall.cou').val(),
        });
    });
    var data = {
        code: $('#code').val(),
        product_name: $('#product_input').val(),
        product_gongyi: $('#product_gy').val(),
        // product_id: $('#product_input option:selected').val(),
        statement: 'add',
        // flow_id: $('#flow_select option:selected').val(),
        number: $('#number').val(),
        remark: $('#remark').val(),
        materials: materials
    };
    $.post('/pages/handler/product_order.php', data, function(r) {
        r = intval(r);
        if (r > 0) {
            parent.Alert('添加成功！');
            window.location.href = '/pages/produce/produce_orders.php';
        } else {
            parent.Alert('添加失败！');
        }
    });
    $.post('/pages/handler/cha_state.php', {
        materials: materials,
        statement: '进行中'
    }, function(r) {

    });
}


/**
 * 下拉框内容改变时的执行函数
 * @param {type} node
 * @param {type} target
 */
function change(node, target) {
    $(target).val($(node).find('option:selected').text());
}

/**
 * 添加车间
 */
function departmentAdd() {
    var department = $('#department_name').val();
    var password = $('#password').val();
    var data = {
        name: department,
        pass: password,
        statement: 'add',
        sort: $('#sort').val()
    };
    if (password !== "" && department !== "") {
        $.post('/pages/handler/department.php', data, function(r) {
            r = parseInt(r);
            if (r > 0) {
                parent.Alert('添加成功！');
                window.location.reload();
            } else {
                parent.Alert('添加失败！');
            }
        });
    }
}

/**
 * 保存车间修改
 * @returns {undefined}
 */

function departmentSave() {
    var data = getSelectedTr();
    var department = $('#department_name').val();
    var password = $('#password').val();
    var id = data[0].id;
    var data = {
        name: department,
        pass: password,
        statement: 'update',
        id: id,
        sort: $('#sort').val()
    };
    if (department !== "") {
        $.post('/pages/handler/department.php', data, function(r) {
            r = parseInt(r);
            if (r > 0) {
                parent.Alert('修改成功！');
                window.location.reload();
            } else {
                parent.Alert('修改失败！');
            }
        });
    }
}

/**
 * 删除车间
 */
function departmentDelete() {
    var data = getSelectedTr()
    if (data !== false) {
        if (confirm('你确认要删除吗')) {
            $.post('/pages/handler/department.php', {
                id: data[0].id,
                statement: 'delete'
            }, function(r) {
                if (r == 1) {
                    parent.Alert('删除成功！');
                    window.location.reload();
                } else {
                    parent.Alert('删除失败！');
                }
            }
            );
        }
    }
}

/**
 * 工作流程设置页面添加流程
 */
function flow_flow_add() {
    var name = $('#input_flow_name').val();
    var department = '';
    var data = {
        name: name,
        departments: department,
        statement: 'add'
    };
    $.post('/pages/handler/flow.php', data, function(r) {
        r = intval(r);
        if (r > 0) {
            $.fancybox.close();
            parent.Alert('添加成功！');
            window.location.reload();
        } else {
            parent.Alert('添加失败！');
        }
    });
}

/**
 * 工作流程设置页面修改流程
 */
function flow_flow_Save() {
    var name = $('#flow_name').val();
    var data = {
        id: current_flow_id,
        statement: 'update',
        name: name
    };
    $.post('/pages/handler/flow.php', data, function(r) {
        if (r == 1) {
            $.fancybox.close();
            parent.Alert('修改成功！');
            window.location.reload();
        } else {
            parent.Alert('修改失败！');
        }
    });
}


/**
 * 工作流程设置页面删除流程
 */
function flow_product_delete() {
    var data = getSelectedTr();
    if (data !== false) {
        if (confirm('你确认要删除吗')) {
            $.post('/pages/handler/flow.php', {
                id: window.current_flow_id,
                statement: 'delete'
            }, function(r) {
                if (r == 1) {
                    parent.Alert('删除成功！');
                    window.location.reload();
                } else {
                    parent.Alert('删除失败！');
                }
            }
            );
        }
    }
}

/**
 * 工作流程设置页面添加车间
 * @returns {undefined}
 */
function flow_department_add() {
    var sort = $('#sort').val();
    var department_id = $('#flow_department_select').val();
    var id = current_flow_id;
    var data = {
        id: id,
        statement: 'save_item',
        departments: [{
                department_id: department_id,
                sort: sort
            }]
    };
    $.post('/pages/handler/flow.php', data, function(r) {
        if (r == 1) {
            parent.Alert('添加成功！');
            window.location.reload();
        } else {
            parent.Alert('添加失败！');
        }
    });

}

/* 
 * ajax获取对应等级的客户列表
 */
function loadCusDataByGroupId(groupId) {
    window.current_groupid = groupId;
    $.get('/pages/ajaxJson/ajax_get_customers.php?id=' + groupId, function(Json) {
        Json = Json.toJson();
        if (Json.length > 0) {
            var tr = '';
            var select = $('#group_select').clone();
            select.attr('id', 'group-input');
            for (var i in Json) {
                if (typeof Json[i] === 'object') {
                    tr += '<tr role="row">';
                    tr += '<td style="display:none;">' + Json[i].customer_id + '</td>';
                    tr += '<td>' + Json[i].customer_name + '</td>';
                    tr += '<td class="f12" style="padding-left: 0">' + Json[i].tel + '</td>';
                    tr += '<td class="f12" style="padding-left: 0">' + Json[i].qq + '</td>';
                    tr += '<td class="f12" style="padding-left: 0">' + Json[i].e_mail + '</td>';
                    tr += '<td class="f12" style="padding-left: 0;width: 300px;">' + Json[i].address + '</td>';
//                    tr += '<td style="padding-left: 0">' + Json[i].remark + '</td>';
                    tr += '<td class="group-td" style="padding-left: 0;display:none;">' + select[0].outerHTML + '</td>';
                    tr += '</tr>';
                }
            }
            $('#custom_det1 tbody').html(tr);
            dataTableLis('#custom_det1');
        } else {
            $('#custom_det1 tbody').html('');
        }
    });
}

// 获取datatable选中项<单选>
function getSelectedTr() {
    if (false === dataTableSelectedTr) {
        return false;
    } else {
        var ret = [];
        var tds = dataTableSelectedTr.find('td');
        tds.each(function(index, node) {
            if ($(node).attr('data-id')) {//如果有data-id属性则返回一个对象，该对象有id和text属性，如果没就返回一个数组，该数组有一个tr上面的所有值
                ret.push({
                    id: $(node).attr('data-id'),
                    text: $(node).text()
                });
            } else {
                ret.push($(node).text());
            }
        });
        return ret;
    }
}

// 获取datatable选中项<多选>
function getMuliSelectedTrs() {
    var trs = $('.dTable tr.click');
    if (trs.length > 0) {
        var ret = [];
        trs.each(function(i, tr) {
            var ret1 = [];
            var tds = $(tr).find('td');
            tds.each(function(index, node) {
                if ($(node).attr('data-id')) {//如果有data-id属性则返回一个对象，该对象有id和text属性，如果没就返回一个数组，该数组有一个tr上面的所有值
                    ret1.push({
                        id: $(node).attr('data-id'),
                        text: $(node).text()
                    });
                } else {
                    ret1.push($(node).text());
                }
            });
            ret.push(ret1);
        });
        return ret;
    } else {
        return false;
    }
}

/**
 * 删除原料信息
 * @returns {undefined}
 */
function materialInfoDelete() {
    var data = getSelectedTr();
    if (data && confirm('你确认删除吗')) {
        $.post('/pages/handler/material_mess.php', {
            id: data[1].id,
            statement: 'delete'
        }, function(r) {
            if (r == 1) {
                parent.Alert('删除成功');
                fnDeleteSelectedTR();
            } else {
                parent.Alert('删除失败');
            }
        });
    }
}

/**
 * 删除产品信息
 * @returns {undefined}
 */
function productInfoDelete() {
    var data = getSelectedTr();
    if (data && confirm('你确认删除吗')) {
        $.post('/pages/handler/product.php', {
            id: data[0],
            statement: 'delete'
        }, function(r) {
            if (r == 1) {
                parent.Alert('删除成功');
                fnDeleteSelectedTR();
            } else {
                parent.Alert('删除失败');
            }
        });
    }
}

/**
 * 
 * @returns {undefined}            
 * $product_id = $product_item['product_id'];
 * mber = $product_item ['number'];
 * $unit_price = $product_item['unit_price'];
 */
function addCustomerOrder() {
    var products = [];
    // getproducts
    $('#productListSelected tbody tr').each(function(i, node) {
        var tds = $('td', node);
        products.push({
            product_id: tds.eq(0).attr('data-id'),
            number: tds.find('.inputSmall.cou').val(),
            unit_price: tds.find('.inputSmall.tot').val(),
            unit_price2: tds.find('.inputSmall.tot1').val() === '' ? 0 : tds.find('.inputSmall.tot1').val()
        });
    });
    $.post('/pages/handler/customer_order.php', {
        statement: 'add',
        customer_id: $('#operator_type_id').val(),
        remark: $('#gs-form-desc').val(),
        products: products,
        amount: cusorderSum,
        amount1: cusorderSum1,
        isdelay: $('#order-delay').val(),
        orderProxy: $('#order-proxy').val(),
        isorderProxy: isorderProxy
    }, function(res) {
        res = parseInt(res);
        if (res > 0) {
            parent.Alert('下单成功');
            window.location.href = '/pages/public/check_detail.php?id=' + res;
//            window.location.href = '/pages/business_department/customers_orders.php';
        } else {
            parent.Alert('下单失败');
        }
    });
}

/**
 * 添加材料订单
 */
function addMaterialOrder() {
    var materials = [];
    // getproducts
    $('#productListSelected tbody tr').each(function(i, node) {
        var tds = $('td', node);
        materials.push({
            material_id: tds.eq(1).attr('data-id'),
            number: tds.find('.inputSmall.cou').val(),
        });
    });
    var data = {
        statement: 'add',
        apply: $('#apply_input').val(),
        remark: $('#gs-form-desc').val(),
        demand_date: $('#demand_date').val(),
        materials: materials,
    };
    $.post('/pages/handler/Material_demand.php', data, function(res) {
        if (res == 1) {
            parent.Alert('下单成功');
            window.location.href = '/pages/workshop/bus_buy_material.php';
        } else {
            parent.Alert('下单失败');
        }
    });
}
/**
 * 采购录入
 * @returns {Function}
 */
function buyMaterial()
{
    var materials = [];
    // getproducts
    $('#productListSelected tbody tr').each(function(i, node) {
        var tds = $('td', node);
        materials.push({
            material_id: tds.eq(1).attr('data-id'),
            number: tds.find('.inputSmall.cou').val(),
            unit_price: tds.find('.inputSmall.tot').val()
        });
    });
    var data = {
        statement: 'add',
        apply: $('#apply_input').val(),
        remark: $('#gs-form-desc').val(),
        materials: materials,
        prices: cusorderSum
    };
    $.post('/pages/handler/Material_buy.php', data, function(res) {
        if (res == 1) {
            parent.Alert('录入成功');
            window.location.href = '/pages/business_department/material.php';
        } else {
            parent.Alert('录入失败');
        }
    });

}
/**
 * 领料录入
 */
function giveMaterial() {
    var materials = [];
    // getproducts
    $('#productListSelected tbody tr').each(function(i, node) {
        var tds = $('td', node);
        materials.push({
            material_id: tds.eq(1).attr('data-id'),
            number: tds.find('.inputSmall.cou').val(),
            // unit_price: tds.find('.inputSmall.tot').val()
        });
    });
    var data = {
        department_id: $('#department_select').val(),
        statement: 'add',
        // apply: $('#apply_input').val(),
        remark: $('#gs-form-desc').val(),
        materials: materials
                //  prices: cusorderSum
    };
    $.post('/pages/handler/Give_material.php', data, function(res) {
        if (res == 1) {
            parent.Alert('录入成功');
            window.location.href = '/pages/business_department/material.php';
        } else {
            parent.Alert('录入失败');
        }
    });
}
/**
 * 查看订单详情
 */
function check_detail() {
    var data = getSelectedTr();
    if (data !== false) {
        $('#check_detail').attr('href', '/../pages/public/check_detail.php?id=' + data[0] + '&state=' + data[7]);
    }
}
/**
 * 查看原料订单详情
 */
function check_material_order_detail() {
    var data = getSelectedTr();
    if (data !== false) {
        $('#check_detail').attr('href', '/../pages/public/check_material_order_detail.php?id=' + data[0] + '&state=' + data[4]);
    }
}

/**
 * 加载工作流程数据
 * @param {type} id
 * @returns {undefined}
 */
function loadFlowMessData(id) {
    window.mSort = 0;
    row = false;
    window.current_flow_id = id;
    $.get('/pages/ajaxJson/ajax_get_flowdata.php?id=' + id, function(Json) {
        Json = Json.toJson();
        var tr = '';
        for (var i in Json) {
            if (Json[i].department_name) {
                mSort = Math.max(mSort, Json[i].sort);
                tr += '<tr class="hovTr" role="row" style="line-height: 45px;height:46px;">';
                tr += '<td class="flow-sort">' + Json[i].sort + '</td>';
                tr += '<td class="flow-department" data-val="' + Json[i].department_id + '">' + Json[i].department_name + '</td>';
                tr += '</tr>';
            }
        }
        $('#workflow-details tbody').html(tr);
        dataTableLis('#workflow-details');
    });
}



/**
 * 流程设置页面车间添加提交
 */
function submit() {
    if (!flowSm) {
        return false;
    }
    $('.flow-input').each(function(i, node) {
        $(node).parent().html($(node).val());
    });
    $('.flow-input1').each(function(i, node) {
        $(node).parent().attr('data-val', $(node).val());
        $(node).parent().html($('option:selected', node).text());
    });
    var id = current_flow_id;
    var departments = [];
    var trs = $('#workflow-details tbody tr');
    trs.each(function(index, node) {
        var tds = $('td', node);//查找每一行tr的td
        departments.push({
            sort: tds.eq(0).text(),
            department_id: tds.eq(1).attr('data-val')
        });
    });

    var data = {
        id: id,
        statement: 'save_item',
        departments: departments
    };
    $.post('/pages/handler/flow.php', data, function(r) {
        r = intval(r);
        if (r > 0) {
            if (window.identify == 1) {
                parent.Alert('添加成功！');
            }
            else if (window.identify == 2) {
                parent.Alert('修改成功！');
            }
            else if (window.identify == 3) {
                parent.Alert('删除成功！');
            }
        } else {
            if (window.identify == 1) {
                parent.Alert('添加失败！');
            }
            else if (window.identify == 2) {
                parent.Alert('修改失败！');
            }
            else if (window.identify == 3) {
                parent.Alert('删除失败！');
            }
        }
        loadFlowMessData(id);
    });
}

/**
 * 流程设置页面增删改
 */
function fnClick(set) {
    window.identify = set;
    if (window.identify === 1) { //添加
        var tr = '';
        flowSm = true;
        var select = $('#flow_department_select').clone();
        select.addClass('flow-input1');
        tr += '<tr role="row" style="line-height:45px;height:46px;">';
        tr += '<td>' + '<input type="text" class="flow-input" style="width:80px;font-size:14px;line-height:21px;" value="' + (++window.mSort) + '">' + '</td>';
        tr += '<td>' + select[0].outerHTML + '</td>';
        tr += '</tr>';
        $('#workflow-details tbody ').append(tr);
        dataTableLis();
    }
    else if (window.identify === 2) { //修改
        if (!row) {
            row = true;
            flowSm = true;
            $('.flow-sort').each(function(i, node) {
                $(node).html('<input type="text" class="flow-input" style="width:80px;font-size:14px;line-height:21px;" value="' + $(node).text() + '"/>');
            });
            $('.flow-department').each(function(i, node) {
                var select = $('#flow_department_select').clone();
                select.addClass('flow-input1');
                $('option', select).each(function(i, opt) {
                    if ($(opt).text() === $(node).text()) {
                        $(opt).attr('selected', 'selected');
                    }
                });
                $(node).html(select);
            });
        }
    }
    else if (window.identify === 3) { //删除
        var data = getSelectedTr();
        if (data && confirm('你确认要删除吗')) {
            flowSm = true;
            $('#workflow-details tbody tr.click').remove();
            $('#workflow-details .flow-sort').each(function(i, node) {
                $(node).html(i + 1);
            });
            submit();
        }
    }
}
/**
 * 原料采购
 * @returns {undefined}
 */
function materialBuy() {
    $.post('/pages/handler/Material_demand.php', {
        remark: $('#remark').val(),
        statement: 'add'
    }, function(mat_id) {
        if (mat_id > 0) {
            $.post('/pages/handler/Material_demand_item.php', {
                material_id: $('#material_name_select').val(),
                demand_id: mat_id,
                statement: 'add',
                number: $('#number').val()
            }, function(ret) {
                if (ret > 0) {
                    parent.Alert('添加订单成功');
                    window.location.reload();
                } else {
                    parent.Alert('添加订单失败');
                }
            });
        } else {
            parent.Alert('添加订单失败');
        }
    });
}

/**
 * 删除客户分组
 * @param {type} id
 * @returns {undefined}
 */
function deleteGroup(id) {
    if (confirm('你确定要删除这个分组吗？该操作无法恢复')) {
        $.post('/pages/handler/group.php', {
            statement: 'delete',
            id: id
        }, function(res) {
            if (res == 1) {
                parent.Alert('删除成功');
                window.location.reload();
            } else {
                parent.Alert('删除失败');
            }
        });
    }
}

/**
 * 查看生产订单详情
 * @returns {undefined}
 */
function viewProduceOrder() {
    var data = getSelectedTr();
    if (data) {
        location.href = '/pages/workshop/view_produce_order.php?id=' + data[0];
    }
}

/**
 * 日
 * 查看生产订单详情2
 * @returns {undefined}
 */
function viewProduceOrder2() {
    var data = getSelectedTr();
    if (data) {
        location.href = '/pages/fac_manager/view_produce_order.php?id=' + data[0];
    }
}


/**
 * 更新客户订单状态
 */
function update_state(condition) {
    if (condition === '已发货' && confirm('你确定要发货吗？一旦发货将扣除相应的成品库存！')) {
        var state = '已发货';
        var id = $('#customer_order_id').text();
        $.post('/pages/handler/customer_order.php', {
            statement: 'state_update',
            order_id: id,
            state: state
        }, function(res) {
            res = intval(res);
            if (res > 0) {
                parent.Alert('订单状态设置成功');
                location.href = '/pages/business_department/customers_orders.php';
            } else {
                parent.Alert('订单状态设置失败');
            }
        });

        var products = [];
        $('tbody .custom_orders_tr ').each(function(i, node) {
            var tds = $('td', node);
            products.push({
                product_id: tds.eq(0).attr('data-id'),
                number: tds.eq(1).text(),
                unit_price: tds.eq(2).text()
            })
        });
        var data = {
            statement: '已发货',
            products: products,
            order_id: id
        };
        $.post('/pages/handler/product_record.php', data, function(res) {

        });

    } else if (condition === '待生产') {
        var state = condition;
        var id = $('#customer_order_id').text();
        $.post('/pages/handler/customer_order.php', {
            statement: 'state_update',
            order_id: id,
            state: state
        }, function(res) {
            res = intval(res);
            if (res > 0) {
                parent.Alert('订单状态设置成功');
                location.href = '/pages/business_department/customers_orders.php';
            } else {
                parent.Alert('订单状态设置失败');
            }
        });
    } else if (condition === '待发货') {
        var state = condition;
        var id = $('#customer_order_id').text();
        $.post('/pages/handler/customer_order.php', {
            statement: 'state_update',
            order_id: id,
            state: state
        }, function(res) {
            res = intval(res);
            if (res > 0) {
                parent.Alert('订单状态设置成功');
                location.href = '/pages/business_department/customers_orders.php';
            } else {
                parent.Alert('订单状态设置失败');
            }
        });
    } else if (condition === '完成订单') {
        var state = '已完成';
        var id = $('#customer_order_id').text();
        $.post('/pages/handler/customer_order.php', {
            statement: 'state_update',
            order_id: id,
            state: state
        }, function(res) {
            res = intval(res);
            if (res > 0) {
                parent.Alert('订单已完成');
                location.href = '/pages/business_department/customers_orders.php';
            } else {
                parent.Alert('操作失败');
            }
        });
    } else {
        parent.Alert('订单状态设置取消');
    }
}

/**
 * 更新采购订单状态
 */
function update_material_order_state(condition) {
    if (condition == '完成订单' && confirm('你要确定完成订单吗?一旦确定则会增加相应的原料库存！')) {
        var state = '已采购';
        var id = $('#customer_order_id').text();
        var data = {
            statement: 'state_update',
            id: id,
            order_state: state
        };
        $.post('/pages/handler/Material_demand.php', data, function(res) {
            if (res == 1) {
                parent.Alert('订单状态设置成功');
                location.href = '/pages/business_department/bus_buy_material.php';
            } else {
                parent.Alert('订单状态设置失败');
            }
        });
        var materials = [];
        $('tbody .custom_orders_tr ').each(function(i, node) {
            var tds = $('td', node);
            materials.push({
                material_id: tds.eq(0).attr('data-id'),
                trade_number: tds.eq(3).text(),
                price: tds.eq(5).text()
            });
        });
        var mdata = {
            statement: '已完成',
            materials: materials
        };
        $.post('/pages/handler/material_record.php', mdata, function(res) {
        });
    } else if (condition == '通过审核') {
        var state = condition;
        var id = $('#customer_order_id').text();
        var data = {
            statement: 'state_update',
            id: id,
            order_state: state
        };
        $.post('/pages/handler/Material_demand.php', data, function(res) {
            if (res == 1) {
                parent.Alert('订单状态设置成功');
                location.href = '/pages/business_department/bus_buy_material.php';
            } else {
                parent.Alert('订单状态设置失败');
            }
        });
    } else if (condition == '未通过审核') {
        var state = condition;
        var id = $('#customer_order_id').text();
        var data = {
            statement: 'state_update',
            id: id,
            order_state: state
        };
        $.post('/pages/handler/Material_demand.php', data, function(res) {
            if (res == 1) {
                parent.Alert('订单状态设置成功');
                location.href = '/pages/business_department/bus_buy_material.php';
            } else {
                parent.Alert('订单状态设置失败');
            }
        });
    } else {
        parent.Alert('订单状态设置取消');
    }

}

/**
 * fancy box 
 * @param {type} nodeId
 * @param {type} callback
 * @returns {undefined}
 */
function fnFancyBox(nodeId, callback) {
    $(nodeId).fancybox({
        'openEffect': 'fade',
        'closeEffect': 'elastic',
        'openSpeed': 'fast',
        'closeSpeed': 'fast',
        'overlayColor': 'blue',
        'scrolling': 'no',
        'afterShow': callback
    });
}

/**
 * 修改保存原料信息详情
 * @param {type} id
 * @param {type} data
 * @returns {undefined}
 */
function materialInfoSave(id, data) {
    $.post('/pages/handler/material_mess.php', data, function(res) {
        if (res > 0) {
            if (window.data_add == 1) {
                parent.Alert('保存成功');
                var html = '';
                html += '<tr style="border-left:1px solid #dedede" class="plS" data-id="' + res + '">';
                html += '<td>' + data.code + '</td>';
                html += '<td data-id="' + res + '">' + data.name + '</td>';
                html += '<td>' + data.type + '</td>';
                html += '<td><input class="inputSmall cou" value="1" /></td>';
                html += '<td><input class="inputSmall tot" style="width:50px" /></td>';
                html += '<td><input class="inputSmall sum" style="width:50px" /></td>';
                html += '<td><a class="delete button" href="javascript:;" >删除</a></td>';
                html += '</tr>';
                $('#productListWrap').show();
                $('#productListSelected tbody').append(html);
                $.fancybox.close();
                //调用删除行函数
                delete_tr();
                resize();
                calculate();
            }
            else {
                parent.Alert('保存成功');
                location.reload();
            }
        } else {
            parent.Alert('保存失败');
        }
    });
}

function productInfoSave(id, data) {
    $.post('/pages/handler/product.php', data, function(res) {
        if (res > 0) {
            if (window.data_add == 1) {
                parent.Alert('保存成功');
                var html = '';
                html += '<tr style="border-left:1px solid #dedede" class="plS" data-id="' + res + '">';
                html += '<td data-id="' + res + '">' + data.model + '(' + data.gongyi + ')</td>';
                html += '<td><input class="inputSmall cou" value="1" /></td>';
                html += '<td><input class="inputSmall tot" style="width:50px" /></td>';
                html += '<td><input class="inputSmall sum" style="width:50px" /></td>';
                html += '<td><input class="inputSmall tot1" style="width:50px" /></td>';
                html += '<td><input class="inputSmall sum1" style="width:50px" /></td>';
                html += '<td><a class="delete button" href="javascript:;" >删除</a></td>';
                html += '</tr>';
                $('#productListWrap').show();
                $('#productListSelected tbody').append(html);
                $.fancybox.close();
                delete_tr();
                resize();
                calculate();
            } else {
                parent.Alert('保存成功');
                location.reload();
            }
        } else {
            parent.Alert('保存失败');
        }
    });
}

function customerGroupSave(data) {

    $.post('/pages/handler/group.php', data, function(res) {
        if (res == 1) {
            parent.Alert('保存成功');
            location.reload();
        } else {
            parent.Alert('保存失败');
        }
    });
}


/**
 * 客户资料增删改函数
 * @param {type} kk
 * @returns {undefined}
 */
function customerInfo(kk) {
    if (kk == 1) {
        window.submit_identify = 1;
        var tr = '';
        tr += '<tr role="row" class="cusAddtr">';
        tr += '<td>' + '<input type="text" class="name-input" />' + '</td>';
        tr += '<td style="padding-left: 0">' + '<input type="text" class="tel-input" />' + '</td>';
        tr += '<td style="padding-left: 0">' + '<input type="text" class="qq-input" />' + '</td>';
        tr += '<td style="padding-left: 0">' + '<input type="text" class="e-mail-input" />' + '</td>';
        tr += '<td style="padding-left: 0">' + '<input type="text" class="address-input" />' + '</td>';
        tr += '<td style="padding-left: 0">' + '<input type="text" class="remark-input" />' + '</td>';
        tr += '</tr>';
        $('#custom_det1 tbody').append(tr);
        dataTableLis('#custom_det1');
    }
    else if (kk == 2) {
        var tr = $('#custom_det1 tbody tr.click');
        tr.addClass('trEditing');
        $('#group').css("display", "inherit");
        $('.group-td select').hide();
        $('.group-td').css("display", "inline");
        $('.group-td select', tr).css("display", "inline");
        window.submit_identify = 2;
        var tds = $('td', tr);
        var data = getSelectedTr();
        $(tds.eq(1)).html('<input type="text" class="name-input"  style="width:87px;" value="' + data[1] + '"/>');
        $(tds.eq(2)).html('<input type="text" class="tel-input"  value="' + data[2] + '"/>');
        $(tds.eq(3)).html('<input type="text" class="qq-input" value="' + data[3] + '"/>');
        $(tds.eq(4)).html('<input type="text" class="e-mail-input" style="width:154px;" value="' + data[4] + '"/>');
        $(tds.eq(5)).html('<input type="text" class="address-input" value="' + data[5] + '"/>');
        $(tds.eq(6)).html('<input type="text" class="remark-input" value="' + data[6] + '"/>');
        $('option', $('#group-input')).each(function(i, opt) {
            if ($(opt).val() == window.current_groupid) {
                $(opt).attr('selected', 'selected');
            }
        });
    }
    else if (kk == 3) {
        window.submit_identify = 3;
        customerSubmit();
    }
}

/**
 * 客户资料操作提交函数
 * @returns {undefined}
 */
function customerSubmit() {
    var id_data = getSelectedTr();
    var data = {
        statement: 'delete',
        id: id_data[0]
    };
    if (confirm('你确认要删除吗')) {
        $.post('/pages/handler/customer.php', data, function(r) {
            if (r == 1) {
                parent.Alert('删除成功');
                fnDeleteSelectedTR();
            } else {
                parent.Alert('删除失败');
            }
        });
    }
}


// 倒计时
function Timer() {

    var self = this;

    this.call = false;

    this.time = [0, 0, 0];

    this.interval = false;

    this.start = function(_call) {
        _call = _call || false;
        this.call = _call;
        this.interval = window.setInterval(self.process, 1000);
    };

    this.pause = function() {
        self.interval = window.clearInterval(self.interval);
    };

    this.clear = function() {
        self.time = [0, 0, 0];
        this.interval = false;
    };

    this.process = function() {
        var push = false;
        var index = 0;
        self.time[2]++;
        for (index in self.time) {
            if (push) {
                self.time[2 - index]++;
                push = false;
                continue;
            }
            if (self.time[2 - index] === 60) {
                self.time[2 - index] = 0;
                push = true;
            }
        }
        push = null;
        index = null;
        if (self.call) {
            self.call(self.time);
        }
    };
}

window.Timer = new Timer();

//回调函数
function timercallback(time) {
    $('#time-span').html(time.join(':'));
}

function setTime() {

}

/**
 * 车间状态更改函数
 * @returns {undefined}
 */
function state_change(set) {
    if (set == 1) {
        var state = '生产中';
        var order_id = parseInt($('#product_order_id').text());
        var department_id = parseInt($('#department_id').text());
        var data = {
            taskstate: state,
            statement: 'state_update',
            department_id: department_id,
            order_id: order_id,
            sort: $('#sort-val').val()
        }
        $.post('/pages/handler/order_department.php', data, function(r) {
            if (r == 1) {
                parent.Alert('任务开始成功');
            } else {
                parent.Alert('任务开始失败');
            }
        });
    }
    if (set == 2) {
        var state = '已暂停';
        var order_id = parseInt($('#product_order_id').text());
        var department_id = parseInt($('#department_id').text());
        var data = {
            taskstate: state,
            statement: 'state_update',
            department_id: department_id,
            order_id: order_id,
            sort: $('#sort-val').val()
        }
        $.post('/pages/handler/order_department.php', data, function(r) {
            if (r == 1) {
                parent.Alert('任务暂停成功');
            } else {
                parent.Alert('任务暂停失败');
            }
        });
    }
    if (set == 3) {
        var state = '已完成';
        var order_id = parseInt($('#product_order_id').text());
        var department_id = parseInt($('#department_id').text());
        var data = {
            taskstate: state,
            statement: 'state_update',
            department_id: department_id,
            order_id: order_id,
            sort: $('#sort-val').val()
        }
        $.post('/pages/handler/order_department.php', data, function(r) {
            if (r == 1) {
                parent.Alert('操作成功');
            } else {
                parent.Alert('操作失败');
            }
        });
    }

}

/**
 * 取消客户订单
 * @returns {undefined}
 */
function cancelCustomOrder() {
    var data = getSelectedTr();
    if (data && confirm('你确定要取消这个订单吗')) {
        $.post('/pages/handler/customer_order.php', {
            order_id: data[0],
            statement: 'delete'
        }, function(res) {
            if (res == 1) {
                parent.Alert('删除成功');
                fnDeleteSelectedTR();
            } else if (res == -1) {
                parent.Alert('删除失败,订单已完成');
            } else {
                parent.Alert('删除失败');
            }
        });
    }
}

/**
 * 生产订单完成
 * @returns {undefined}
 */
function produceOrderFinish() {
    if ($('#productNum1').val() !== '' && confirm('订单编号为 ' + $('#pdcode').val() + ' 的生产订单已经完成了吗')) {
        $.post('/pages/handler/product_order.php', {
            id: $('#pdid').val(),
            statement: 'finish',
            finish_number: parseInt($('#productNum1').val())
        }, function(r) {
            r = parseInt(r);
            if (r > 0) {
                parent.Alert('生产已完成');
            } else {
                parent.Alert('操作失败');
            }
            $.fancybox.close();
        });
    }
}

/**
 * 取消生产订单
 * @returns {undefined}
 */
function cancelProductOrder() {
    if (confirm('你确定要取消这个订单吗')) {
        $.post('/pages/handler/product_order.php', {
            id: $('#pdid').val(),
            statement: 'delete'
        }, function(res) {
            res = intval(res);
            if (res > 0) {
                parent.Alert('删除成功');
                location.href = '/pages/produce/produce_orders_finished.php';
            } else if (res === -1) {
                parent.Alert('删除失败,订单已完成');
            } else {
                parent.Alert('删除失败');
            }
        });
    }
}

/**
 * 取消原料采购订单
 * @returns {undefined}
 */
function cancelMaterialOrder() {
    var data = getSelectedTr();
    if (data && confirm('你确定要取消这个订单吗')) {
        $.post('/pages/handler/Material_demand.php', {
            id: data[0],
            statement: 'delete'
        }, function(res) {
            if (res == 1) {
                parent.Alert('删除成功');
                fnDeleteSelectedTR();
            } else if (res == -1) {
                parent.Alert('删除失败,订单已完成');
            } else {
                parent.Alert('删除失败');
            }
        });
    }
}

/**
 * 修改操作员页面弹出后显示函数
 */
function show_all() {
    if ($('#operator_type_id').val() == 4) {
        $('#department_div').slideDown(100);
    }
    else {
        $('#department_div').slideUp(100);
    }
}

/**
 * 加载搜索左方数据块
 * @param {type} html
 * @returns {undefined}
 */
function loadTop(html) {
    $('#topLeftPlace').html(html);
}

/**
 * 客户短信群发
 * @returns {undefined}
 */
function customer_groupmessage() {
    var head = '', content = '', phones = [];
    head = $('#department_name').val();
    content = $('#content').val();
    $('#custom_det2 tr.click .cusphone').each(function(i, node) {
        phones.push($.trim($(node).text()));
    });
    phones = $.trim(phones);
    if (head !== '' && content !== '' && phones !== '') {
        if (confirm('你确定要群发吗')) {
            $.get('/pages/handler/sendmessages.php?phones=' + phones + '&cont=【' + head + '】' + content, function(res) {
                res = res.toJson();
                alert(res.msg);
                location.reload();
            });
        }
    } else {
        if (head === '') {
            parent.Alert('请输入公司名称', true);
        } else if (content === '') {
            parent.Alert('请输入群发内容', true);
        } else if (phones === '') {
            parent.Alert('请选择群发客户', true);
        }

    }
}

/**
 * 数组转int
 * @param {type} arr
 * @returns {unresolved}
 */
function arrayInt(arr) {
    var i = 0;
    for (i in arr) {
        arr[i] = parseInt(arr[i]);
    }
    i = null;
    return arr;
}

/**
 * 为原料的data_add赋值函数
 */
function give() {
    window.data_add = $('#productInfoAdd').attr('data_add');
}

function give_material() {
    window.data_add = $('#materalInfoAdd').attr('data_add');
}


/**
 * 删除订单行函数
 */
function delete_tr() {
    $('.delete').click(function() {
        $(this).parent().parent().remove();
    });
}

/**
 * 计算函数
 */
function calculate() {
    $('.inputSmall.cou').keyup(function() {
        $(this).parent().parent().find('.sum').val($(this).parent().parent().find('.tot').val() * $(this).val());
        $(this).parent().parent().find('.sum1').val($(this).parent().parent().find('.tot1').val() * $(this).val());
        countOrderSum();
    });
    $('.inputSmall.tot').keyup(function() {
        $(this).parent().parent().find('.sum').val($(this).parent().parent().find('.cou').val() * $(this).val());
        countOrderSum();
    });
    $('.inputSmall.sum').keyup(function() {
        $(this).parent().parent().find('.tot').val($(this).val() / $(this).parent().parent().find('.cou').val());
        countOrderSum();
    });
    $('.inputSmall.tot1').keyup(function() {
        $(this).parent().parent().find('.sum1').val($(this).parent().parent().find('.cou').val() * $(this).val());
        countOrderSum();
    });
    $('.inputSmall.sum1').keyup(function() {
        $(this).parent().parent().find('.tot1').val($(this).val() / $(this).parent().parent().find('.cou').val());
        countOrderSum();
    });
    function countOrderSum() {
        cusorderSum = 0;
        $('.inputSmall.sum').each(function(i, node) {
            var val = parseInt($(node).val());
            if (!isNaN(val)) {
                cusorderSum += val;
            }
        });
        $('#order_sum').html('&yen;' + cusorderSum);
        countOrderSum1();
    }
    function countOrderSum1() {
        cusorderSum1 = 0;
        $('.inputSmall.sum1').each(function(i, node) {
            var val = parseInt($(node).val());
            if (!isNaN(val)) {
                cusorderSum1 += val;
            }
        });
        isorderProxy = cusorderSum1 > 0 ? 1 : 0;
        $('#order_sum1').html('&yen;' + cusorderSum1);
    }
}

/**
 * 删除已选中的tr
 * @returns {undefined}
 */
function fnDeleteSelectedTR() {
    dataTableSelectedTr.fadeOut();
}

function goBack() {
    history.go(-1);
}

/**
 * 修改用户密码
 * @returns {undefined}
 */
function change_userpass() {
    var _old = $('#old_pass').val();
    var _new = $('#new_pass').val();
    if (_old !== '' && _new !== '') {
        $.post('/pages/handler/ajax_change_pass.php', {
            _old: _old,
            _new: _new
        }, function(r) {
            if (r > 0) {
                parent.Alert('修改成功');
            } else {
                parent.Alert('修改失败', true);
            }
        });
    }
}

/**
 * 生产仓库入库
 * @returns {undefined}
 */
function productTransfer() {
    var count = parseInt($('#tf_count').val());
    var productId = parseInt($('#tf_product').val());
    var remark = $('#remark').val();

    if (count > 0 && productId > 0) {
        $.post("/pages/handler/ajax_productTransfer.php", {
            count: count,
            productId: productId,
            remark: remark
        }, function(r) {
            r = parseInt(r);
            if (r > 0) {
                parent.Alert('入库成功');
                goBack();
            } else {
                parent.Alert('入库失败，库存不足以入库', true);
            }
        });
    }
}

/**
 * 快速销售出库
 * @returns {undefined}
 */
function fastSale() {
    var order_amount = parseFloat($('#tf_amount').val());
    order_amount = isNaN(order_amount) ? 0 : order_amount;
    var order_count = parseInt($('#tf_count').val());
    if (order_count > 0) {
        var products = [{
                product_id: intval($('#tf_product').val()),
                number: intval($('#tf_count').val()),
                unit_price: order_amount > 0 ? (order_amount / intval($('#tf_count').val())) : 0,
                unit_price2: 0
            }];

        // 获取客户id，byname
        if ($('#cusname').val() !== '') {
            $.post('/pages/ajaxJson/ajax_get_customerId_byname.php', {
                name: $('#cusname').val()
            }, function(r) {
                r = r.toJson();
                _f1(r.id);
            });
        } else {
            _f1(0);
        }

        function _f1(customer_id) {
            $.post('/pages/handler/customer_order.php', {
                statement: 'add',
                customer_id: customer_id,
                remark: $('#remark').val(),
                products: products,
                amount: order_amount,
                amount1: 0,
                isdelay: '',
                orderProxy: 0,
                isorderProxy: 0
            }, function(res) {
                res = parseInt(res);
                if (res > 0) {
                    parent.Alert('下单成功');
                    // 标记订单完成 扣除库存
                    var data = {
                        statement: '已完成',
                        products: products,
                        order_id: res
                    };
                    $.post('/pages/handler/product_record.php', data, function(res) {
                        console.log(res);
                    });
                } else {
                    parent.Alert('下单失败');
                }
            });
        }
    }
}

function intval(r) {
    return parseInt(r);
}

function debug(m) {
    if (console)
        console.log(m);
}